/**
 * Express 本地服务器
 * @author Saeki
 */
var path = require('path');
var opn = require('opn')
var express = require('express');
var webpack = require('webpack');
var merge = require("webpack-merge");
var config = require("./config.js")

console.log('> 加载配置文件');
var webpackConfig = require('./develop.config.js');

console.log('> 实例化 Webpack 编译器');
var compiler = webpack(webpackConfig)

console.log("> 初始化 Express 中间件");
var devMiddleware = require('webpack-dev-middleware')(compiler, {
    publicPath: webpackConfig.output.publicPath,
    quiet: true
});

var hotMiddleware = require('webpack-hot-middleware')(compiler);

compiler.plugin('compilation', function(compilation) {
    compilation.plugin('html-webpack-plugin-after-emit', function(data, cb) {
        hotMiddleware.publish({ action: 'reload' })
        cb()
    })
})

console.log("> 启动 Express");
var app = express();

app.use(devMiddleware)
app.use(hotMiddleware)

devMiddleware.waitUntilValid(function() {
    opn("http://127.0.0.1:" + config.port + "/document.html")
    console.log('> 本地开发服务器完成启动');
})

module.exports = app.listen(config.port, function(err) {
    if (err) {
        console.log(err)
        return
    }
})